﻿using Excel;
using Microsoft.WindowsAPICodePack.Dialogs;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ExcelToJson
{
    public partial class Form1 : Form
    {
        private HashSet<string> pathList = new HashSet<string>();
        private string initDir;
        private static TextBox staticLogTxt;
        public Form1()
        {
            InitializeComponent();
            excelDirTxt.Text = Directory.GetCurrentDirectory();
            jsonDitTxt.Text = Directory.GetCurrentDirectory();
            codeDirTxt.Text = Directory.GetCurrentDirectory();
            initDir = excelDirTxt.Text;
            timer1.Start();
            staticLogTxt = logTxt;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (CommonOpenFileDialog dialog = new CommonOpenFileDialog())
            {
                dialog.IsFolderPicker = true;
                dialog.RestoreDirectory = true;
                dialog.InitialDirectory = initDir;
                if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
                {
                    this.excelDirTxt.Text = dialog.FileName;//G:\新建文件夹
                    this.refreshExcelPath();
                }
            }

        }
        private void refreshExcelPath()
        {
            this.pathList.Clear();
            excelCheckBoxList.Items.Clear();
            string curExcelDirTxt = this.excelDirTxt.Text;
            DirectoryInfo dir = new DirectoryInfo(curExcelDirTxt);
            foreach (var file in dir.GetFiles())
            {
                if (file.Name.Contains(".xlsx"))
                {
                    if (file.Name.Contains("~$"))
                    {
                        continue;
                    }
                    pathList.Add(file.Name);
                    excelCheckBoxList.Items.Add(file.Name);
                }
            }
        }

        private void checkRreshPath()
        {
            string curExcelDirTxt = this.excelDirTxt.Text;
            DirectoryInfo dir = new DirectoryInfo(curExcelDirTxt);
            var files = dir.GetFiles().ToList();
            foreach (var file in files)
            {
                if (file.Name.Contains(".xlsx"))
                {
                    if (file.Name.Contains("~$"))
                    {
                        continue;
                    }
                    if (!pathList.Contains(file.Name))
                    {
                        pathList.Add(file.Name);
                        excelCheckBoxList.Items.Add(file.Name);
                    }
                }
            }
            List<string> delList = new List<string>();
            foreach (string path in pathList)
            {
                FileInfo file = files.Find(f => f.Name == path);
                if (file == null)
                {
                    delList.Add(path);
                }
            }
            foreach (string delPath in delList)
            {
                pathList.Remove(delPath);
                excelCheckBoxList.Items.Remove(delPath);
            }
        }
        private void log(string txt)
        {
            this.logTxt.Text += txt + "\r\n";
        }
        public static void logInfo(string txt)
        {
            staticLogTxt.Text += txt + "\r\n";
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            checkRreshPath();
        }

        private void openJsonDirBtn_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("explorer.exe", jsonDitTxt.Text);
        }

        private void openCodeDitBtn_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("explorer.exe", codeDirTxt.Text);
        }

        private void allSelectBtn_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < excelCheckBoxList.Items.Count; i++)
            {
                excelCheckBoxList.SetItemChecked(i, true);
            }
        }
        private List<string> getSelectExcelPath()
        {
            List<string> selectPathList = new List<string>();
            for (int i = 0; i < excelCheckBoxList.CheckedItems.Count; i++)
            {
                string path = excelDirTxt.Text + "\\" + excelCheckBoxList.GetItemText(excelCheckBoxList.CheckedItems[i]);
                selectPathList.Add(path);
            }
            return selectPathList;
        }

        private void exportJsonBtn_Click(object sender, EventArgs e)
        {
            List<string> selectPaths = getSelectExcelPath();
            foreach(string selectPath in selectPaths)
            {
                exportExcel(selectPath);
            }
        }
        private void exportExcel(string path)
        {
            FileStream mStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            IExcelDataReader mExcelReader = ExcelReaderFactory.CreateOpenXmlReader(mStream);
            DataSet mResultSet = mExcelReader.AsDataSet();
            if (mResultSet.Tables.Count < 1)
            {
                log(path + "表数量小于1");
                return;
            }
            List<ExcelClass> excelClasses = new List<ExcelClass>();
            for (int i=0;i< mResultSet.Tables.Count;i++)
            {
                DataTable dataTable = mResultSet.Tables[i];
                ExcelClass excelClass= new ExcelClass(dataTable);
                excelClasses.Add(excelClass);
            }

            if (mergeJsonCB.Checked)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("{");
                for(int i=0;i<excelClasses.Count;i++)
                {
                    sb.Append(excelClasses[i].ExportJsonInTableName());
                    if (i != excelClasses.Count-1)
                    {
                        sb.AppendLine(",");
                    }
                    {
                        sb.AppendLine();
                    }
                }
                sb.AppendLine("}");
                string jsonPath=jsonDitTxt.Text+"\\"+ Path.GetFileNameWithoutExtension(path)+".json";
                WriteFile(jsonPath, sb.ToString(), Encoding.UTF8);
            }
            else
            {
                for (int i = 0; i < excelClasses.Count; i++)
                {
                    string jsonStr = excelClasses[i].ExportJson();
                    string jsonPath = jsonDitTxt.Text + "\\" + excelClasses[i].className + ".json";
                    WriteFile(jsonPath, jsonStr, Encoding.UTF8);
                }
            }
        }
        private void jsonDirBtn_Click(object sender, EventArgs e)
        {
            using (CommonOpenFileDialog dialog = new CommonOpenFileDialog())
            {
                dialog.IsFolderPicker = true;
                dialog.RestoreDirectory = true;
                dialog.InitialDirectory = initDir;
                if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
                {
                    this.jsonDitTxt.Text = dialog.FileName;//G:\新建文件夹
                }
            }
        }

        private void codeDirBtn_Click(object sender, EventArgs e)
        {
            using (CommonOpenFileDialog dialog = new CommonOpenFileDialog())
            {
                dialog.IsFolderPicker = true;
                dialog.RestoreDirectory = true;
                dialog.InitialDirectory = initDir;
                if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
                {
                    this.codeDirTxt.Text = dialog.FileName;//G:\新建文件夹
                }
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("explorer.exe", excelDirTxt.Text);
        }
        public static void WriteFile(string path,string content ,Encoding encoding)
        {
            //写入文件
            using (FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
            {
                using (TextWriter textWriter = new StreamWriter(fileStream, encoding))
                {
                    textWriter.Write(content);
                }
            }
        }

        private void excelCheckBoxList_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
